﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace UtilsExtensionsAndHelpers.Utils
{
    public abstract class BaseInMemoryRepository<TEntity,TId> : IRepository<TEntity,TId> where TEntity : IEntity<TId>
    {
        public Func<TEntity> New { get; set; }
        public Action<TEntity> SetNewId { get; set; }

        protected List<TEntity> _itemList = new List<TEntity>();

        public bool Exists(TId id)
        {
            return _itemList.Any(i => i.Id.Equals(id));
        }

        public TEntity Get(TId id)
        {
            return _itemList.FirstOrDefault(i => i.Id.Equals(id));
        }

        public TEntity Save(TEntity item)
        {
            if (item == null) throw new ArgumentNullException();

            if (Exists(item.Id)) {
                var itemIndex = _itemList.IndexOf(item);
                _itemList[itemIndex] = item;
            } else {
                SetNewId(item);
                _itemList.Add(item);
            }

            return item;
        }

        public IEnumerable<TEntity> List()
        {
            return _itemList;
        }

        public void Delete(TEntity item)
        {
            if (item == null) throw new ArgumentNullException();

            _itemList.Remove(item);
        }

        public void Delete(TId id)
        {
            Delete(Get(id));
        }
    }
}
